import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
   private ServerSocket socket ;
   public TcpEchoServer(int port) throws IOException {
       this.socket = new ServerSocket(port);
   }
   public void start() throws IOException {
       System.out.println("服务器启动");
       //用线程池处理 连接
       ExecutorService service = Executors.newCachedThreadPool();
       while (true){
          // 获取连接
           Socket clientSocket = this.socket.accept();   // 获取socket
           // 处理连接
           service.submit(()->{
               try {
                   processConnection(clientSocket);
               } catch (IOException e) {
                   throw new RuntimeException(e);
               }
           })  ;

       }


   }
     // 处理连接
    private void processConnection(Socket clientSocket) throws IOException {
          // 获得到连接就表示有客户端上线
        System.out.println("客户端上线: ip: "+clientSocket.getInetAddress()+" port:"+clientSocket.getPort());
         try(  InputStream inputStream = clientSocket.getInputStream() ;
               OutputStream outputStream = clientSocket.getOutputStream()){
            // 通过Scanner来读
               while (true){
                   Scanner scan = new Scanner(inputStream) ;
                   // 没有数据过来就断开连接
                   if(!scan.hasNext()){
                       System.out.println("客户端下线: ip:"+clientSocket.getInetAddress() +" port "+clientSocket.getPort());
                       break;
                   }
                   String request = scan.next() ;
                   String response = process(request);
                   // 用一个write来写,并且能在数据后面加上 /n
                   PrintWriter writer = new PrintWriter(outputStream) ;
                   writer.println(response);
                   // 刷新一下writer
                   writer.flush();
                 // 打印日志
                   System.out.println("请求:"+request + " "+response);
               }

         }finally {
             clientSocket.close();   // 防止文件泄露
        }
    }

    private String process(String request) {
       return "响应:"+request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(7070);
        tcpEchoServer.start();
    }
}
